<template>
	<view class="pagehome">
		<view class="tp-box tp-box-sizing tp-pd-l-r-30">
			<!-- 未登录 -->
			<view class="noLogin" v-if="!isLogin">
				<view class="fishlogo"><img src="/static/icon/fisheryLogo.png"></view>
				<view class="authLogin">
					<!-- 获取微信绑定的手机号 -->
					<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
						v-if="isGetPhone">获取手机号并登录</button>
					<button @click="toLogin" v-else>点击登录</button>
				</view>
			</view>
			<!-- 已登录 -->
			<view v-else :style="{marginTop: marginTop}">
				<!-- <view class="tp-status-bar"></view> -->
				<view class="tp-fishery-select tp-flex tp-flex-row tp-flex-j-l tp-flex-a-c">
					<view v-if="ytData.length >0" style="display: flex;" @click="toMore">
						<text class="tp-mg-r-10 yttitle">{{ytTitle}}</text>
						<view class="iconfont iconjiantou" style="margin-top: 10rpx;"></view>
					</view>
					<button class="addyt" v-else @click="$refs.addpopup.open()">添加鱼塘</button>
					<view class="moreitem" v-if="ytData.length>0&&isMore">
						<view class="item_i" v-for="(m,i) in ytData" :key="i" @click="changYt(m)">{{m.title}}</view>
						<view class="addytt" @click="$refs.addpopup.open()"> + 添加鱼塘</view>
					</view>
				</view>
				<view class="tp-grid-three tp-mg-t-25"
					v-if="boxData.widget_identifier && (boxData.widget_identifier=='fisheriesscreen:screen'||boxData.widget_identifier=='intelligentscreen:surroundings')">
					<view class="tp-panel tp-flex tp-flex-row tp-flex-j-s tp-flex-a-c tp-box-sizing tp-pd-20"
						style="background: #207AF5;margin-right: 29rpx;">
						<view class="tp-flex tp-flex-col">
							<view style="color: #fff;" v-if="rjyData.latest">{{rjyData.latest[1]}}<text
									class="tp-mg-l-05" style="color: #fff;">mg/L</text></view>
							<view class="tp-mg-t-05" style="color: #fff;" v-if="rjyData.name">{{rjyData.name}}</view>
						</view>
						<view>
							<image src="/static/icon/icon-oxygen.png"></image>
						</view>
					</view>
					<view class="tp-panel tp-flex tp-flex-row tp-flex-j-s tp-flex-a-c tp-box-sizing tp-pd-20">
						<view class="tp-flex tp-flex-col">
							<view v-if="phData.latest">{{phData.latest[1]}}<text class="tp-mg-l-05"
									style="white-space:nowrap;">PH值</text></view>
							<view class="tp-mg-t-05" v-if="phData.name">{{phData.name}}</view>
							<!-- <view v-if="phData.latest_value">{{phData.latest_value}}</view>
							<view class="tp-mg-t-05">PH值</view> -->
						</view>
						<view>
							<image src="/static/icon/icon-ph.png"></image>
						</view>
					</view>
					<view class="tp-panel tp-flex tp-flex-row tp-flex-j-s tp-flex-a-c tp-box-sizing tp-pd-20">
						<view class="tp-flex tp-flex-col">
							<view v-if="swData.latest">{{swData.latest[1]}}<text class="tp-mg-l-05"
									style="white-space:nowrap;">水温</text></view>
							<view class="tp-mg-t-05" v-if="swData.name">{{swData.name}}</view>
							<!-- <view>{{waterTemperature}}<text class="tp-mg-l-05">&#176;C</text></view>
							<view class="tp-mg-t-05">水温</view> -->
						</view>
						<view>
							<image src="/static/icon/icon-water-temperature.png"></image>
						</view>
					</view>
				</view>
				<view class="tp-title tp-mg-t-25" style="margin-top: 51rpx; margin-bottom: 48rpx;">设备状态
					<view class="tp-add" @click="addEqp"> + 添加设备</view>
				</view>
				<view class="tp-panel-two tp-mg-t-25"
					v-if="boxData.widget_identifier=='fisheriesscreen:screen' || boxData.widget_identifier == 'intelligentscreen:surroundings'">
					<block v-for="(item,index) in deviceData" :key="index">
						<view
							class="tp-flex tp-flex-row tp-flex-j-s tp-flex-a-c tp-box-sizing tp-pd-l-r-20 tp-pd-t-b-15 eq_item"
							:class="!item.status?'tp-device-close':''">
							<view class="tp-flex tp-flex-row">
								<view class="tp-mg-t-b-10 iconfontImg">
									<img :src="item.icon" v-if="item.status == 0">
									<img :src="item.iconActive" v-if="item.status == 1">
								</view>
								<view style="margin-left: 24rpx;">
									<view class="tp-mg-b-05 sp_item_title">{{item.title}}</view>
									<view class="tp-mg-b-05 sp_item_status" v-if="item.status == 0">关闭</view>
									<view class="tp-mg-b-05 sp_item_status" v-if="item.status == 1">开启</view>
								</view>
							</view>
							<view>
								<view class="tp-flex tp-flex-j-c tp-flex-a-c switch" @click="changSwitch(item,index)">
									<img src="/static/icon/switch_on.png" v-if="item.status == 1">
									<img src="/static/icon/switch_close.png" v-if="item.status == 0"></text>
								</view>
							</view>
						</view>
					</block>
				</view>
				<view class="tp-title tp-mg-t-25" style="margin-top: 75rpx; margin-bottom: 36rpx;">操作日志与状态</view>
				<block>
					<view class="tp-log tp-flex tp-flex-col tp-mg-t-15">
						<!-- <view class="tp-log-title tp-mg-t-15 tp-mg-b-20">{{item.date}}<text>/{{item.month}}月</text>
						</view> -->
						<view class="tp-panel tp-flex tp-flex-col tp-box-sizing tp-pd-20"
							v-for="(item,index) in logData" :key="index">
							<!-- <block v-for="(items,indexs) in item.list" :key="indexs"> -->
							<view class="tp-log-item tp-flex tp-flex-row tp-flex-j-s tp-flex-a-c">
								<view class="tp-circle tp-mg-l-r-20" :class="index==0?'tp-active':'' "
									style="margin-left: 10rpx;">
									<!-- {{item.status}} -->
								</view>
								<view class="tp-flex-1">{{item.describe}}</view>
								<view class="tp-time">{{item.created_at}}</view>
								<!-- <view>
										<image :src="items.icon"></image>
									</view> -->
							</view>
							<!-- </block> -->
						</view>
					</view>
				</block>
				<view class="tp-tmp"></view>
			</view>
		</view>
		<!-- 添加鱼塘 -->
		<uni-popup ref="addpopup" :mask-click="false">
			<view class="add">
				<view class="addtitle">添加鱼塘</view>
				<view class="addcontent">
					<input type="text" placeholder="请输入鱼塘" v-model="ytName" />
				</view>
				<view class="addbtn">
					<button @click="$refs.addpopup.close()" class="cancelbtn">取消</button>
					<button @click="toAddConfirm" class="confirmbtn">确定</button>
				</view>
			</view>
		</uni-popup>
		<!-- 授权登录 -->
		<uni-popup ref="authPopup" type="bottom">
			<authorize @getuserinfo="getAuth" @cancel="toCloseLogin"></authorize>
		</uni-popup>
		<!-- 消息提示框 -->
		<cys-toast ref="toast" :msg="toast.msg" :direction="row" location="top"></cys-toast>
	</view>
</template>

<script>
	var socketOpen = false;
	var socketMsgQueue = {
		wid: '',
		config: {
			startTs: '0',
			endTs: '0',
			latestTime: '10',
			operator: 'AVG',
			interval: '15000'
		}
	};
	var Dissolved_Oxygen1, PH1, temperature1;
	//
	import {
		mapState
	} from "vuex";
	//
	export default {
		data() {
			return {
				ytTitle: '',
				socketTask: null,
				socketSwitchTask: null,
				marginTop: 0,
				isMore: false,
				ytName: '',
				isGetPhone: false,
				fishery: 1000,
				oxygen: 66,
				ph: 6.5,
				waterTemperature: 20,
				deviceData: [{
						id: 1001,
						icon: '/static/icon/zy_close.png',
						iconActive: '/static/icon/zy_on.png',
						title: '增氧',
						status: ''
					},
					{
						id: 1002,
						icon: '/static/icon/sl_close.png',
						iconActive: '/static/icon/sl_on.png',
						title: '饲料',
						status: ''
					},
					{
						id: 1002,
						icon: '/static/icon/sb_close.png',
						iconActive: '/static/icon/sb_on.png',
						title: '水泵',
						status: ''
					}
				],
				logData: [],
				userInfo: {
					isAuth: false,
					isLogin: false,
				},
				isLogin: false,
				wxData: {
					iv: '',
					encryptedData: '',
				},
				toast: {
					msg: ''
				},
				ytData: [],
				currentDashboardId: '', //当前渔场的id
				boxData: {},
				rjyData: {
					name: '',
					latest: [],
				},
				phData: {
					name: '',
					latest: [],
				},
				swData: {
					name: '',
					latest: [],
				},
				rjyname: '',
			}
		},
		// 
		onLoad(e) {

		},
		//
		onShow() {
			if (this.$login.isLoginType().isLogin) {
				this.getYTData()
			}
			if (this.$login.isLoginType().isAuth) {
				this.isGetPhone = true
			}
			let systemInfo = wx.getSystemInfoSync();
			// px转换到rpx的比例
			let pxToRpxScale = 750 / systemInfo.windowWidth;
			// 状态栏的高度
			let ktxStatusHeight = systemInfo.statusBarHeight * pxToRpxScale;
			// 导航栏的高度
			let navigationHeight = 44 * pxToRpxScale;
			this.marginTop = ktxStatusHeight + 'rpx';
			this.isLogin = this.$login.isLoginType().isLogin
		},
		// 关闭websocket【必须在实例销毁之前关闭,否则会是underfined错误】
		beforeDestroy() {
			this.closeSocket();
		},
		//
		methods: {
			//控制设备开关
			changSwitch(item, index) {
				this.toWebSocket(item, index)
			},
			//获取操作日志
			getWarningList() {
				uni.showLoading({
					title: '加载中'
				});
				this.API.apiRequest('/warning/index', {}, 'post').then(res => {
					if (res.code === 200) {
						this.logData = res.data
						// 调用WebSocket
						this.toWebSocket()
					}
					uni.hideLoading()
				});
			},
			//添加设备
			addEqp() {
				let _this = this
				// 允许从相机和相册扫码
				uni.scanCode({
					success: function(res) {
						let result = res.result
						//激活设备
						_this.API.apiRequest('/device/scan', {
							code: result,
							dashboard_id: _this.currentDashboardId,
						}, 'post').then(res => {
							if (res.code === 200) {
								_this.getBox()
							} else {
								this.toast.msg = res.message;
								this.$refs.toast.show();
							}
						});
					}
				});
			},
			//切换鱼塘
			changYt(m) {
				this.ytTitle = m.title
				this.isMore = false
				this.closeSocket();
				this.currentDashboardId = m.id
				this.getBox()
			},
			//查看更多鱼塘
			toMore() {
				this.isMore = true
			},
			//获取渔塘信息
			getYTData() {
				uni.showLoading({
					title: '加载中'
				});
				this.API.apiRequest('/dashboard/index', {}, 'post').then(res => {
					if (res.code === 200) {
						this.ytData = res.data.data
						this.currentDashboardId = res.data.data[0].id
						this.ytTitle = res.data.data[0].title
						this.getBox()
					}
					uni.hideLoading()
				});
			},
			//获取box信息
			getBox() {
				var newData = {};
				uni.showLoading({
					title: '加载中'
				});
				this.API.apiRequest('/dashboard/dashboard', {
					chart_id: this.currentDashboardId
				}, 'post').then(res => {
					if (res.code == 200) {
						if (res.data.length > 0) {
							newData = res.data[0]
							this.getWarningList()
						}
						this.boxData = newData
					}
					uni.hideLoading()
				})
			},
			//调用WebSocket
			toWebSocket(epq, index) {
				this.closeSocket();
				let that = this
				socketMsgQueue.wid = that.boxData.id
				//建立websoket连接
				that.socketTask = uni.connectSocket({
					url: 'wss://qiyuan.jiyikeji.cn/ws?token=' + uni.getStorageSync(
						'access_token'),
					success: (suc) => {
						console.log("websoket已连接")
					}
				});
				//改变状态 
				if (epq) {
					var newStatus;
					if (epq.status == 0) {
						newStatus = 1
					}
					if (epq.status == 1) {
						newStatus = 0
					}
					switch (index) {
						case 0:
							socketMsgQueue = {
								wid: that.boxData.id,
								config: {
									startTs: '0',
									endTs: '0',
									latestTime: '10',
									operator: 'AVG',
									interval: '15000'
								},
								message: {
									switch: {
										relay1: newStatus
									},
								}
							};
							that.deviceData[0].status = newStatus
							break;
						case 1:
							socketMsgQueue = {
								wid: that.boxData.id,
								config: {
									startTs: '0',
									endTs: '0',
									latestTime: '10',
									operator: 'AVG',
									interval: '15000'
								},
								message: {
									switch: {
										relay2: newStatus
									},
								}
							};
							that.deviceData[1].status = newStatus
							break;
						default:
							socketMsgQueue = {
								wid: that.boxData.id,
								config: {
									startTs: '0',
									endTs: '0',
									latestTime: '10',
									operator: 'AVG',
									interval: '15000'
								},
								message: {
									switch: {
										relay9: newStatus
									},
								}
							};
							that.deviceData[2].status = newStatus
							break;
					}
				}
				//发送消息
				that.socketTask.onOpen(function(res) {
					socketOpen = true;
					if (socketOpen) {
						that.socketTask.send({
							data: JSON.stringify(socketMsgQueue)
						});
					}
					socketMsgQueue = {
						wid: '',
						config: {
							startTs: '0',
							endTs: '0',
							latestTime: '10',
							operator: 'AVG',
							interval: '1000'
						}
					}
				});
				//监听服务器返回
				that.socketTask.onMessage(function(res) {
					// let _this = this
					if (res.data.indexOf('Welcome to ThingsPanel') != -1) {
						console.log("232323")
					} else {
						var olddata = res.data.replace(/\ufeff/g, ""); //字符串转化JSON对象
						var data = JSON.parse(olddata).data;
						that.rjyData = data.Dissolved_Oxygen1
						that.phData = data.PH1
						that.swData = data.temperature1
						// relay1 对应增氧开关,
						// relay2对应饲料开关，
						// relay9对应水泵开关  0关  1开
						that.deviceData[0].status = data.relay1
						that.deviceData[1].status = data.relay2
						that.deviceData[2].status = data.relay9
					}

				});
			},
			// 关闭websocket
			closeSocket() {
				try {
					this.socketTask.close({
						success(res) {
							socketOpen = false;
							console.log("关闭成功", res)
						},
						fail(err) {
							console.log("关闭失败", err)
						}
					})
				} catch (e) {
					//TODO handle the exception
				}
			},
			//判断是不是json字符串
			isJSON(str) {
				if (typeof str == 'string') {
					try {
						var obj = JSON.parse(str);
						if (typeof obj == 'object' && obj) {
							return true;
						} else {
							return false;
						}

					} catch (e) {
						console.log('error：' + str + '!!!' + e);
						return false;
					}
				}
			},
			//添加鱼塘
			toAddConfirm() {
				if (this.ytName == '') {
					this.toast.msg = '请输入鱼塘名称';
					this.$refs.toast.show();
				} else {
					uni.showLoading({
						title: '加载中'
					});
					this.API.apiRequest('/dashboard/paneladd', {
						title: this.ytName,
						business_id: '92a00bb5-f28e-4849-baa5-f1edd85649e6'
					}, 'post').then(res => {
						if (res.code == 200) {
							this.ytName = ''
							this.toast.msg = res.msg;
							this.$refs.toast.show();
							this.$refs.addpopup.close()
							this.getYTData()
						}
						uni.hideLoading()
					});
				}
			},
			//获取绑定的手机号
			getPhoneNumber(e) {
				this.wxData = e.detail
				this.isGetPhone = false
				this.toLogin()
			},
			//登录
			toLogin() {
				let that = this
				if (!that.$login.isLoginType().isAuth) {
					that.$refs.authPopup.open()
				} else {
					// 获取用户信息
					uni.login({
						success(res) {
							uni.setStorageSync('wx_code', res.code)
							let url = "/auth/login";
							let data = {
								login_type: 'wechatmini',
								business_id: '92a00bb5-f28e-4849-baa5-f1edd85649e6',
								wx_code: uni.getStorageSync('wx_code'),
								iv: that.wxData.iv,
								encryptedData: that.wxData.encryptedData,
								name: JSON.parse(uni.getStorageSync('userWxInfo')).nickName,
							};
							uni.showLoading({
								title: '加载中'
							});
							that.API.apiRequest(url, data, 'post').then(res => {
								if (res.code === 200) {
									uni.showToast({
										title: '登录成功',
										icon: 'none'
									});
									uni.setStorageSync('access_token', res.data.access_token)
									that.userInfo = that.$login.isLoginType()
									that.isLogin = true
									that.$forceUpdate()
									that.getYTData()
								} else {
									that.toast.msg = res.msg;
									that.$refs.toast.show();
								}
								uni.hideLoading()
							});
						}
					});
				}
			},
			//关闭
			toCloseLogin() {
				this.$refs.authPopup.close()
			},
			//获取授权
			getAuth() {
				var that = this;
				//判断是否授权
				uni.getUserProfile({
					desc: '登录',
					success(infoRes) {
						const userInfo = infoRes.userInfo;
						uni.setStorageSync('userWxInfo', JSON.stringify(userInfo))
						uni.setStorageSync('isAuth', '1')
						that.isGetPhone = true
						that.$refs.authPopup.close()

					},
					fail: err => {
						console.log('未授权err==', err);
					}
				});
			},

		}
	}
</script>
<style>
	page {}
</style>
<style scoped lang="css">
	@import '@/common/fishery-monitor.css';

	.pagehome {
		background: url() no-repeat center center;
		height: 100%;
		background-size: cover;
	}
</style>
